require 'date';

class ProjectController < ApplicationController

  # add project
  def add
    return unless params[:form_submitted];

    @project = Project.new(params[:project]);
    return unless @project.save();

    flash[:info_msg] = "New project has been added";
    redirect_to(:controller => 'project', :action => 'list');
  end
  
  # show project
  def show
    get_project;
    @comments = @project.comments;
  end

  # edit project
  def edit
    get_project;
    return unless params[:form_submitted];
    return unless @project.update_attributes(params[:project]);
    
    flash[:info_msg] = "Project updated";
    redirect_to(:controller => 'project', :action => 'list', :id => @project.is_open == 0 ? 'closed' : nil);
  end


  # list projects
  def list
      @projects = (params[:id] == 'closed') ? Project.closed_projects : Project.opened_projects;
  end

  # tasks
  def tasks 
    get_project;
    @tasks = @project.active_tasks;
  end

  # add comment
  def add_comment
    get_project;
    return unless params[:form_submitted];
   
    @comment_project = CommentProject.new({ 
        :content    => params[:comment_project][:content] ,
        :project_fk => @project.project_id ,
        :added      => DateTime.now() ,
	:user_fk    => session[:user].user_id 
	});
    return unless @comment_project.save();

    flash[:info_msg] = 'Comment added';
    redirect_to(:controller => 'project', :action => 'show', :id => @project.project_id);
  end

  protected
  # get project
  def get_project(project_id = nil)
    project_id = params[:id] unless project_id;
    unless (project_id)
      flash[:error_msg] = "No project selected";
      redirect_to(:controller => 'project', :action => 'list');
      return;
    end
    unless (project_id =~ /^\d+$/) 
      flash[:error_msg] = "Invalid project id";
      return;
    end
    @project = Project.get_project(project_id); 
    unless (@project) 
      flash[:error_msg] = "No project found";
      redirect_to(:controller => 'project', :action => 'list');
      return;
    end
    return @project;
  end

end
